var meeting_hot;
var counter=0;
var pageNavObj = null;
var current=0;
var modify_add_flg=0;
var modify_add_id=null;
$(function () {
    getAll(0);
    // 初始化时间选择器
    $("#timePicker_0").daterangepicker({
        timePicker: true,
        startDate: moment().startOf('hour'),
        endDate: moment().startOf('hour').add(32, 'hour'),
        timePicker24Hour:true,
        locale: {
            format: 'YYYY/MM/DD hh:mm A'
        }
    },function (start,end,label) {
        this.element.attr("start",Date.parse(start));
        this.element.attr("end",Date.parse(end));
    });
    $("#timePicker_0").attr("start",moment().startOf('hour'));
    $("#timePicker_0").attr("end",moment().startOf('hour').add(32, 'hour'));
});
// 创建表格
function createTable(datas,num) {
    if(datas!=null){
        var data=[];
        $.each(datas,function (e,v) {
            var list={"name":v.name,"cost":v.cost,"cycle":v.cycle,"operation":"","id":v.id};
            data.push(list);
        });
        if(num==0){
            var operation=function(instance, td, row, col, prop, value, cellProperties){
                Handsontable.renderers.TextRenderer.apply(this, arguments);
                td.innerHTML="";
                var div=$("<div>" +
                    "<button type='button' id='modify' meeting_id='"+instance.getDataAtRowProp(row,"id")+"' class='btn btn-default modify' data-toggle='modal' data-target='#modifyBody'>修改</button>" +
                    "<button type='button' id='delete' meeting_id='"+instance.getDataAtRowProp(row,"id")+"' class='btn btn-default delete'>删除</button>" +
                    "<button type='button' id='meeting_export' meeting_id='"+instance.getDataAtRowProp(row,"id")+"' class='btn btn-default meeting_export'>导出参会用户</button></div>");
                $(td).append(div);
            };
            var container = document.getElementById('table_meeting');
            meeting_hot = new Handsontable(container, {
                data: data,
                autoColumnSize:true,
                rowHeaders: false,
                colHeaders: ["会议名称","报名费用","会议时长","操作"],
                fillHandle:true,
                hiddenColumns: {
                    columns: [4]
                },
                cells: function (row, col, prop){
                    var cellProperties = {};
                    if(col==3){
                        cellProperties.renderer = operation;
                    }
                    cellProperties.readOnly = true;
                    return cellProperties;
                }
            });
            $("#table_meeting").siblings("#hot-display-license-info").css("display","none");
        }else{
            meeting_hot.loadData(data);
            current=num;
        }
        modifyShow();
        meeting_delete();
        meeting_export();
    }
}
function modifyShow() {
    modify_add_flg=1;
    // 修改点击事件
    $(".modify").on("click",function () {
        var id=$(this).attr("meeting_id");
        var params=JSON.stringify({"conferenceId":id});
        modify_add_id=id;
        $.ajax({
            // url:'http://125.65.40.171/conference-check/conferenceController/selectConferenceInfo',
            url:'conferenceController/selectConferenceInfo',
            dataType:'json',
            data:{"param":params},
            type:"post",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success:function (data) {
                if(data.code==200){
                    $("#meeting_name").val(data.data[0].name);
                    $("#meeting_cost").val(data.data[0].cost);
                    $("#meeting_cycle").val(data.data[0].cycle);
                    $.each(data.data[0].addressList,function (e,v) {
                        if(e>0){
                            $("#plus").click();
                        }
                        $(".form_meeting").find("tbody").find("tr:last").find(".timePicker").daterangepicker({timePicker: true, startDate:new Date(v.startDate).Format("yyyy/MM/dd HH:mm"), endDate: new Date(v.endDate).Format("yyyy/MM/dd HH:mm"),locale: {format: 'YYYY/MM/DD hh:mm A'},timePicker24Hour:true },function (start,end,label) {
                            this.element.attr("start",Date.parse(start));
                            this.element.attr("end",Date.parse(end));
                        });
                        $(".form_meeting").find("tbody").find("tr:last").find(".timePicker").attr("start",v.startDate);
                        $(".form_meeting").find("tbody").find("tr:last").find(".timePicker").attr("end",v.endDate);
                        $(".form_meeting").find("tbody").find("tr:last").find(".site").val(v.site);
                        $(".form_meeting").find("tbody").find("tr:last").find(".count").val(v.content);
                        $(".form_meeting").find("tbody").find("tr:last").find(".member").val(v.distinguishedGuest);
                        $(".form_meeting").find("tbody").find("tr:last").find(".remark").val(v.remark);
                    })
                }else if(data.code==500){
                    alert("当前没有数据");
                }
            },
            error:function (XMLHttpRequest,textStatus,errorThrown) {
                alert('系统错误');
            }
        })
    })
}
function meeting_delete() {
    $(".delete").on("click",function () {
        var id=$(this).attr("meeting_id");
        var params=JSON.stringify({"conferenceId":id});
        $.ajax({
            // url:'http://125.65.40.171/conference-check/conferenceController/deleteConferenceByPrimaryKey',
            url:'conferenceController/deleteConferenceByPrimaryKey',
            dataType:'json',
            data:{"param":params},
            type:"post",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success:function (data) {
                if(data.code==200){
                    window.location.href="manage";
                }else if(data.code==500){
                    alert("删除失败");
                }
            },
            error:function (XMLHttpRequest,textStatus,errorThrown) {
                alert('系统错误');
            }
        })
    });
}
function meeting_export() {
    $(".meeting_export").on("click",function () {
        var id = $(this).attr("meeting_id");
        // window.open("http://125.65.40.171/conference-check/exportExcelController/exportAttendRecordInfoByConferenceId?conferenceId="+id);
        window.open("exportExcelController/exportAttendRecordInfoByConferenceId?conferenceId="+id);
    });
}
// 获取所有数据
function getAll(num) {
    var par=0;
    if(num==0){
        par=1;
    }else{
        par=num;
    }
    var params=JSON.stringify({"pageNumber":par});
    $.ajax({
        // url:'http://125.65.40.171/conference-check/conferenceController/selectAllConference',
        url:'conferenceController/selectAllConference',
        dataType:'json',
        data:{"param":params},
        type:"post",
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        success:function (data) {
            if(data.code==200){
                createTable(data.data.dataList,num);
                // 初始化分页
                if(current==num){
                    pageNavObj = new PageNavCreate("PageNavId",{
                        pageCount:data.data.pageTotal,//总页数
                        currentPage:par,//当前页
                        perPageNum:5//每页按钮数
                    });
                    pageNavObj.afterClick(pageNavCallBack);
                }
            }else if(data.code==500){
                createTable(null,num);
                alert("当前没有数据");
            }
        },
        error:function (XMLHttpRequest,textStatus,errorThrown) {
            alert('系统错误');
        }
    })
}
// 添加按钮点击事件
$("#plus").on("click",function(){
    counter++;
    $(".form_meeting").find("tbody").append($(".form_meeting").find("tbody").find("tr:last").clone());
    $(".form_meeting").find("tbody").find("tr:last").find(".timePicker").attr("id","timePicker_"+counter);
    $("#timePicker_"+counter).daterangepicker({
        timePicker: true,
        startDate: moment().startOf('hour'),
        endDate: moment().startOf('hour').add(32, 'hour'),
        timePicker24Hour:true,
        locale: {
            format: 'YYYY/MM/DD hh:mm A'
        }
    },function (start,end,label) {
        this.element.attr("start",Date.parse(start));
        this.element.attr("end",Date.parse(end));
    });
});
// 删除按钮点击事件
$("#minus").on("click",function () {
    if($(".form_meeting").find("tbody").find("tr").length>1){
        $(".form_meeting").find("tbody").find("tr:last").remove();
    }
});
//翻页按钮点击后触发的回调函数
function pageNavCallBack(clickPage){
    // console.log(clickPage);
    // 更新分页插件
    // pageNavCreate("PageNav",pageCount,clickPage,pageNavCallBack);
    pageNavObj = new PageNavCreate("PageNavId",{
        pageCount:getPageSet().pageCount,//总页数
        currentPage:clickPage,//当前页
        perPageNum:getPageSet().perPageNum,//每页按钮数
    });
    pageNavObj.afterClick(pageNavCallBack);
    if(current!=clickPage){
        getAll(clickPage);
    }
}
function getPageSet(){
    var obj = {
        pageCount:null,//总页数
        currentPage:null,//当前页
        perPageNum:null,//每页按钮数
    }
    if($("#testPageCount").val() && !isNaN(parseInt($("#testPageCount").val()))){
        obj.pageCount = parseInt($("#testPageCount").val());
    }else{
        obj.pageCount = parseInt($(".page-input-box > input").attr("placeholder"));
    }
    if($("#testCurrentPage").val() && !isNaN(parseInt($("#testCurrentPage").val()))){
        obj.currentPage = parseInt($("#testCurrentPage").val());
        obj.currentPage = (obj.currentPage<=obj.pageCount ? obj.currentPage : obj.pageCount);
    }else{
        obj.currentPage = 1;
    }
    if($("#testPerPageNum").val() && !isNaN(parseInt($("#testPerPageNum").val()))){
        obj.perPageNum = parseInt($("#testPerPageNum").val());
    }else{
        obj.perPageNum = null;
    }
    return obj;
}
$("#meeting_add").on("click",function () {
    modify_add_id=null;
    modify_add_flg=0;
});
$(".submit").on("click",function () {
    $(".form_sub").click();
});
// 添加会议
$("form").submit(function (e) {
    var name=$(this).find("#meeting_name").val();
    var cost=$(this).find("#meeting_cost").val();
    var cycle=$(this).find("#meeting_cycle").val();
    var rwm=$(this).find("#meeting_ewm").val();
    var timeFlg=false;
    var siteFlg=false;
    var flg=false;
    $.each($(this).find(".timePicker"),function (e,v) {
        if($(v).attr("start")==null){
            timeFlg=true;
        }
    });
    $.each($(this).find(".site"),function (e,v) {
        if($(v).val()==""){
            siteFlg=true;
        }
    });
    if(name==""){
        alert("会议名称不能为空");
        e.preventDefault();
    }else{
        if(cost==""){
            alert("报名费用不能为空");
            e.preventDefault();
        }else{
            if(cycle==""){
                alert("会议时长不能为空");
                e.preventDefault();
            }else{
                if(rwm==""){
                    alert("二维码不能为空");
                    e.preventDefault();
                }else{
                    if(timeFlg){
                        alert("会议时间不能为空");
                        e.preventDefault();
                    }else{
                        if(siteFlg){
                            alert("会议地点不能为空");
                            e.preventDefault();
                        }else{
                            flg=true;
                        }
                    }
                }
            }
        }
    }
    if(flg){
        var branch=[];
        $.each($(this).find("tbody").find("tr"),function (e,v) {
            var obj={
                "site":$(v).find(".site").val(),
                "content":$(v).find(".count").val(),
                "startDate":$(v).find(".timePicker").attr("start"),
                "endDate":$(v).find(".timePicker").attr("end"),
                "remark":$(v).find(".remark").val(),
                "distinguishedGuest":$(v).find(".member").val()
            };
            branch.push(obj);
        });
        var main_par={"name":name, "cost":cost,"cycle":cycle,"id":modify_add_id};
        var fileObj=document.getElementById("meeting_ewm").files[0];
        var formFile = new FormData();
        formFile.append("file", fileObj); //加入文件对象
        formFile.append("isEdit", modify_add_flg); //加入文件对象
        formFile.append("conferenceJson", JSON.stringify(main_par)); //加入文件对象
        formFile.append("addressListJson", JSON.stringify(branch)); //加入文件对象
        $.ajax({
            // url:'http://125.65.40.171/conference-check/conferenceController/createConference',
            url:'conferenceController/createConference',
            dataType:'json',
            async:false,
            data:formFile,
            type:"post",
            traditional: true,
            cache:false,         //不设置缓存
            processData: false,  // 不处理数据
            contentType: false, // 不设置内容类型
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success:function (data) {
                if(data.code==200){
                    alert("添加成功");
                }else if(data.code==500){
                    e.preventDefault();
                    alert("添加失败");
                }
            },
            error:function (XMLHttpRequest,textStatus,errorThrown) {
                // e.preventDefault();
                // alert('系统错误');
            }
        });
    }
});
$(".sub_close").on("click",function () {
    $(".form_meeting")[0].reset();
    $(".form_meeting").find("tbody").find("tr:not(tr:first)").remove();
});
//input只能输入数字
function clearNoNum(obj){
    //修复第一个字符是小数点 的情况.
    if(obj.value !=''&& obj.value.substr(0,1) == '.'){
        obj.value="";
    }
    obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
    if(obj.value.indexOf(".")< 0 && obj.value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if(obj.value.substr(0,1) == '0' && obj.value.length == 2){
            obj.value= obj.value.substr(1,obj.value.length);
        }
    }
}
